<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

//Redirect to another page or site
function util_redirect($url = '', $msg = '', $prefix = false) {
	//
	$pos = strpos($url, '?');
	if( $pos === false ) {
		//
	} else {
		$url = substr($url, 0, $pos + 1) . str_replace('?', '%3F', substr($url, $pos + 1));
	}
	//
	if( is_array($msg) ) {
		foreach($msg as $k => $v) {
			$msg_url = urlencode($k) . '=' . urlencode($v) . '&';
		}
		if( substr($msg_url, -1) == '&' ) {
			$msg_url = substr($msg_url, 0, -1);
		}
	} elseif( $msg ) {
		$msg_url = 'msg=' . urlencode($msg);
	} else {
		$msg_url = '';
	}
	if( trim($msg_url) ) {
	 	if( strpos($url, '?') !== false ) {
			$url .= '&' . $msg_url;
		} else {
			$url .= '?' . $msg_url;
		}
	}
	if( $prefix == false ) {
		$url = CONFIG_URL_HTTP . $url;
	}

	if( headers_sent() ) {
		echo '<script language="javascript" type="text/javascript">document.location.href="' . $url . '";</script>';
	} else {
		header('Location: ' . $url);
	}
	exit();
}

//exit
function util_exit() {
	func_session_close();
	exit();
}

//ajax
function util_ajax_exit() {
	if( IS_AJAX ) {
		util_exit();
	}
}

//guid format
function util_guid() {
	mt_srand((double)microtime()*1000000);
	$s = md5(mt_rand() . microtime());
	
	return substr($s, 0, 8) . '-' . substr($s, 8, 4) . '-' . substr($s, 12, 4) . '-' . substr($s, 16, 4) . '-' . substr($s, 20, 12);
}

//parse link
function util_parse_link($request_uri) {
	$link_result = array();
	
	//xml
	if( substr($request_uri, 0, strlen('xml/')) == 'xml/' ) {
		$link_result = array(
					'type' => 'xml',
					'link' => substr($request_uri, strlen('xml/'))
						);
	} else {
		//parse
		if( strpos($request_uri, '/') === false ) {
			if( substr($request_uri, -strlen(CONFIG_URL_SUFFIX)) == CONFIG_URL_SUFFIX ) {
				$link_result = array(
							'type' => substr($request_uri, 0, -strlen(CONFIG_URL_SUFFIX)),
							'link' => ''
								);
			} else {
				$link_result = array(
							'type' => $request_uri,
							'link' => ''
								);
			}
		} else {
			$link_result = array(
						'type' => substr($request_uri, 0, strpos($request_uri, '/')),
						'link' => substr($request_uri, strpos($request_uri, '/') + 1)
							);
		}
	}
	

	return $link_result;
}

//request_type
//request_link_class
//request_link_subclass
function util_link_filter($link) {
	$link = ereg_replace("[^A-Za-z0-9\-\_]", '', $link);
	$link = substr($link, 0, 50);
	
	return $link;
}

//
function util_file_exists($prefix, $value, $suffix, $type = 'request_link_class') {
	$valuef = util_link_filter($value);
	if( file_exists($prefix . $valuef . $suffix) ) {
		if( $value != $valuef ) {
			global $$type;
			$$type = $valuef;
		}
		
		return true;
	}
	
	return false;
}

//Parse the data used in the html tags to ensure the tags will not break
function util_string_parse_input_data($data, $parse) {
	return strtr(trim($data), $parse);
}

function util_string_output($string, $translate = false, $protected = false) {
	if( $protected == true ) {
		return htmlspecialchars($string);
	} else {
		if( $translate == false ) {
			return util_string_parse_input_data($string, array('"' => '&quot;'));
		} else {
			return util_string_parse_input_data($string, $translate);
		}
	}
}

function util_string_output_protected($string) {
	return util_string_output($string, false, true);
}

function util_string_sanitize($string) {
	$string = ereg_replace(' +', ' ', $string);
	return preg_replace("/[<>]/", '_', $string);
}

function util_string_to_int($string) {
	return (int)$string;
}

function util_string_split($string, $length = 2000) {
	$ss = array();
	$count = 0;
	$strlen = strlen($string);
	while($count < $strlen) {
		$str = util_substr($string, $count, $length);
		if( $str == '' ) {
			break;
		}
		$ss[] = $str;
		$count += strlen($str);
	}
	
	return $ss;
}

// Break a word in a string if it is longer than a specified length ($len)
function util_string_break($string, $len, $break_char = '-') {
	$l = 0;
	$output = '';

	for($i=0, $n=strlen($string); $i<$n; $i++) {
		$char = substr($string, $i, 1);
		if( $char != ' ' ) {
			$l++;
		} else {
			$l = 0;
		}
		if( $l > $len ) {
			$l = 1;
			$output .= $break_char;
		}
		$output .= $char;
	}

	return $output;
}

function util_htmlspecialchars($string) {
	if( is_array($string) ) {
		foreach($string as $key => $val) {
			$string[$key] = util_htmlspecialchars($val);
		}
	} else {
		$string = preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $string));
	}
	
	return $string;
}

function util_htmlfilter($string) {
	if( is_array($string) ) {
		foreach($string as $key => $val) {
			$string[$key] = util_htmlfilter($val);
		}
	} elseif( $string != '' ) {
		$pattern = array(
				"/\s/",
				"/<(\/?)(script|i?frame|style|html|body|title|link|object|meta|\?|\%)([^>]*?)>/isU", 
				"/(<[^>]*)on[a-zA-Z]\s*=([^>]*>)/isU",
					);
		$replace = array(
				" ",
				"&lt;\\1\\2\\3&gt;",
				"\\1\\2",
					);
		$string = preg_replace($pattern, $replace, $string);
	}
	
	return $string;
}

function util_addslashes($string, $type = 'string') {
	if( $type == 'object' && is_object($string) ) {
		foreach($string as $k => $v) {
			$string->$k = util_addslashes($v);
		}
	} else {
		$string = is_array($string) ? array_map('util_addslashes', $string) : addslashes($string);
	}
	
	return $string;
}

function util_stripslashes($string, $type = 'string') {
	if( $type == 'object' && is_object($string) ) {
		foreach($string as $k => $v) {
			$string->$k = util_stripslashes($v);
		}
	} else {
		$string = is_array($string) ? array_map('util_stripslashes', $string) : stripslashes($string);
	}
	
	return $string;
}

/**
* Strip slashes from strings or arrays of strings
* @param value the input string or array
*/
function util_stripslashes_ds(&$value) {
	$ret = '';
	if( is_string($value) ) {
		//$ret = big5_stripslashes($value);
		$ret = $value;
	} else {
		if( is_array($value) ) {
			$ret = array();
			while(list($key,$val) = each($value) ) {
				$ret[$key] = util_stripslashes($val);
			} // while
		} else {
			$ret = $value;
		} // if
	}// if
	
	return $ret;
}

function util_substr($string, $start, $length = 0) {
	$strlen = strlen($string);
	if( $start < 0 ) {
		$start = $strlen + $start;
	}
	if( $length == 0 ) {
		$length = max(0, $strlen - $start);
	}
	if( $strlen > $start + $length + 1 ) {
		$strlen = $start + $length;
	}
	
	//fix start
	for($i=0; $i<$start; $i++) {
		if( ord(substr($string, $i, 1)) > 127 ) {//0xa0
			$i = $i + 2;
		} else {
			//
		}
	}
	$start = $i;
	
	$tmpstr = '';
	for($i=$start; $i<$strlen; $i++) {
		if( ord(substr($string, $i, 1)) > 127 ) {//0xa0
			$tmpstr .= substr($string, $i, 3);
			$i = $i + 2;
		} else {
			$tmpstr .= substr($string, $i, 1);
		}
	}
	
	return $tmpstr;
}

// nl2br() prior PHP 4.2.0 did not convert linefeeds on all OSs (it only converted \n)
function util_convert_linefeeds($from, $to, $string) {
	if( (PHP_VERSION < "4.0.5") && is_array($from) ) {
		return ereg_replace('(' . implode('|', $from) . ')', $to, $string);
	} else {
		return str_replace($from, $to, $string);
	}
}

function util_row_number_format($number, $length = '3') {
	if( ($number < 10) && (substr($number, 0, 1) != '0') ) {
		$number = '0' . $number;
	}
	
	return $number;
}

function util_word_count($string, $needle) {
	$temp_array = split($needle, $string);
	
	return sizeof($temp_array);
}

function util_array_to_string($array, $exclude = '', $equals = '=', $separator = '&') {
	if( !is_array($exclude) ) {
		$exclude = array();
	}
	
	$get_string = '';
	if( sizeof($array) > 0 ) {
		while(list($key, $value) = each($array)) {
			if( (!in_array($key, $exclude)) && ($key != 'x') && ($key != 'y') ) {
				$get_string .= $key . $equals . $value . $separator;
			}
		}
		$remove_chars = strlen($separator);
		$get_string = substr($get_string, 0, -$remove_chars);
	}
	
	return $get_string;
}

function util_not_null($value) {
	if( is_array($value) ) {
		if( sizeof($value) > 0 ) {
			return true;
		} else {
			return false;
		}
	} else {
		if( (is_string($value) || is_int($value) || is_numeric($value)) && ($value != '') && ($value != 'NULL') && (strlen(trim($value)) > 0) ) {
			return true;
		} else {
			return false;
		}
	}
}

function util_header($string, $replace = true, $http_response_code = 0) {
	$string = str_replace(array("\r", "\n"), array('', ''), $string);
	if( empty($http_response_code) || PHP_VERSION < '4.3' ) {
		@header($string, $replace);
	} else {
		@header($string, $replace, $http_response_code);
	}
	if( preg_match('/^\s*location:/is', $string) ) {
		exit();
	}
}

function util_get_all_get_params($exclude_array = '') {
	if( !is_array($exclude_array)) $exclude_array = array();
	
	$get_url = '';
	if( is_array($_GET) && (sizeof($_GET) > 0) ) {
		reset($_GET);
		while( list($key, $value) = each($_GET) ) {
			if( (strlen($value) > 0) && ($key != session_name()) && ($key != 'error') && (!in_array($key, $exclude_array)) && ($key != 'x') && ($key != 'y') ) {
				$get_url .= $key . '=' . rawurlencode(stripslashes($value)) . '&';
			}
		}
	}
	
	return $get_url;
}

//Utility function to return a value from a named array or a specified default
define("_STRING_NOTRIM", 0x0001);
define("_STRING_ALLOWHTML", 0x0002);
function util_get_param(&$arr, $name, $def=null, $mask=0) {
	$return = null;
	if( isset($arr[$name]) ) {
		if( is_string($arr[$name]) ) {
			if( !($mask&_STRING_NOTRIM) ) {
				$arr[$name] = trim($arr[$name]);
			}
			if( !($mask&_STRING_ALLOWHTML) ) {
				$arr[$name] = strip_tags($arr[$name]);
			}
			if( !get_magic_quotes_gpc() ) {
				$arr[$name] = addslashes($arr[$name]);
			}
		}
		return $arr[$name];
	} else {
		return $def;
	}
}

//browser detect
function util_browser_detect($component) {
	return stristr($_SERVER['HTTP_USER_AGENT'], $component);
}

//Checks the user agent string against known browsers
function util_get_browser($agent) {
	require_once(CONFIG_PATH . CONFIG_DIR_INCLUDES . 'agent_browser.php');

	if( preg_match( "/msie[\/\sa-z]*([\d\.]*)/i", $agent, $m )
	&& !preg_match( "/webtv/i", $agent )
	&& !preg_match( "/omniweb/i", $agent )
	&& !preg_match( "/opera/i", $agent ) ) {
		// IE
		return "MS Internet Explorer $m[1]";
	} elseif( preg_match( "/netscape.?\/([\d\.]*)/i", $agent, $m ) ) {
		// Netscape 6.x, 7.x ...
		return "Netscape $m[1]";
	} elseif( preg_match( "/mozilla[\/\sa-z]*([\d\.]*)/i", $agent, $m )
			&& !preg_match( "/gecko/i", $agent )
			&& !preg_match( "/compatible/i", $agent )
			&& !preg_match( "/opera/i", $agent )
			&& !preg_match( "/galeon/i", $agent )
			&& !preg_match( "/safari/i", $agent ) ) {
		// Netscape 3.x, 4.x ...
		return "Netscape $m[2]";
	} else {
		// Other
		$found = false;
		foreach( $browserSearchOrder as $key ) {
			if( preg_match( "/$key.?\/([\d\.]*)/i", $agent, $m ) ) {
				$name = "$browsersAlias[$key] $m[1]";
				return $name;
				break;
			}
		}
	}

	return 'Unknown';
}

//check is from browser
function util_check_from_browser() {
	static $r = -1;
	if( $r === -1 ) {
		$r = 0;
		$ua = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
		if( $ua && ((strpos($ua, 'mozilla') !== false) || (strpos($ua, 'msie') !== false) || (strpos($ua, 'gecko') !== false) || (strpos($ua, 'opera') !== false)) ) {
			$r = 1;
		}
	}
	
	return $r;
}

//Checks the user agent string against known operating systems
function util_get_OS($agent) {
	require("includes/agent_os.php");

	foreach( $osSearchOrder as $key ) {
		if( preg_match( "/$key/i", $agent ) ) {
			return $osAlias[$key];
			break;
		}
	}

	return 'Unknown';
}

//ip address
function util_get_ip_address() {
	if( isset($_SERVER) ) {
		if( isset($_SERVER['HTTP_X_FORWARDED_FOR']) ) {
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} elseif( isset($_SERVER['HTTP_CLIENT_IP']) ) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
	} else {
		if( getenv('HTTP_X_FORWARDED_FOR') ) {
			$ip = getenv('HTTP_X_FORWARDED_FOR');
		} elseif( getenv('HTTP_CLIENT_IP') ) {
			$ip = getenv('HTTP_CLIENT_IP');
		} else {
			$ip = getenv('REMOTE_ADDR');
		}
	}
	
	return $ip;
}

//robot
function util_get_robot() {
	if( !defined('IS_ROBOT') ) {
		$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
		$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
		
		if( preg_match("/($kw_browsers)/", $_SERVER['HTTP_USER_AGENT']) ) {
			define('IS_ROBOT', FALSE);
		} elseif( preg_match("/($kw_spiders)/", $_SERVER['HTTP_USER_AGENT']) ) {
			define('IS_ROBOT', TRUE);
		} else {
			define('IS_ROBOT', FALSE);
		}
	}
	
	return IS_ROBOT;
}

//referer
function util_get_referer($default = '') {
	global $referer, $indexname;

	$default = empty($default) ? $indexname : '';
	if(empty($referer) && isset($GLOBALS['_SERVER']['HTTP_REFERER'])) {
		$referer = preg_replace("/([\?&])((sid\=[a-z0-9]{6})(&|$))/i", '\\1', $GLOBALS['_SERVER']['HTTP_REFERER']);
		$referer = substr($referer, -1) == '?' ? substr($referer, 0, -1) : $referer;
	} else {
		$referer = util_htmlspecialchars($referer);
	}

	if(!preg_match("/(\.php|[a-z]+(\-\d+)+\.html)/", $referer) || strpos($referer, 'logging.php')) {
		$referer = $default;
	}
	
	return $referer;
}

// os crlf
function util_get_crlf() {
	$ua = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
	if( $ua ) {
		if( stristr(strtolower($ua), 'win') !== false ) {
			return "\r\n";
		} elseif( stristr(strtolower($ua), 'win') !== false ) {
			return "\r";
		} else {
			return "\n";
		}
	}
	
	return "\n";
}

function util_get_crlf_str() {
	$ua = isset($_SERVER['HTTP_USER_AGENT']) ? strtolower($_SERVER['HTTP_USER_AGENT']) : '';
	if( $ua ) {
		if( stristr(strtolower($ua), 'win') !== false ) {
			return '\r\n';
		} elseif( stristr(strtolower($ua), 'win') !== false ) {
			return '\r';
		} else {
			return '\n';
		}
	}
	
	return '\n';
}

function util_text_split($text, $s = false) {
	if( $s == true ) {
		$crlf = util_get_crlf_str();
	} else {
		$crlf = util_get_crlf();
	}
	
	return explode($crlf, $text);
}

//cookie
function util_setcookie($name, $value = '', $expire = 0, $path = '/', $domain = '', $secure = 0) {
	//$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	setcookie($name, $value, $expire, $path, (util_not_null($domain) ? $domain : ''), $secure);
}

function util_getcookie($name, $value = '') {
	return isset($_COOKIE[$key]) ? $_COOKIE[$key] : $value;
}

//json
function util_json_encode($value) {
	if( function_exists('json_encode') ) {
		return json_encode($value);
	}
	$props = '';
	if(is_object($value)) {
		foreach (get_object_vars($value) as $name => $propValue) {
			if( isset($propValue) ) {
				$props .= $props ? ','.util_json_encode($name)  : util_json_encode($name);
				$props .= ':' . util_json_encode($propValue);
			}
		}
		return '{' . $props . '}';
	} elseif (is_array($value)) {
		$keys = array_keys($value);
		if (!empty($value) && !empty($value) && ($keys[0] != '0' || $keys != range(0, count($value)-1))) {
			foreach ($value as $key => $val) {
				$key = (string) $key;
				$props .= $props ? ','.util_json_encode($key)  : util_json_encode($key);
				$props .= ':' . util_json_encode($val);
			}
			return '{' . $props . '}';
		} else {
			$length = count($value);
			for ($i = 0; $i < $length; $i++) {
				$props .= $props ? ','.util_json_encode($value[$i])  : util_json_encode($value[$i]);
			}
			return '[' . $props . ']';
		}
	} elseif (is_string($value)) {
		$replace  = array('\\' => '\\\\', "\n" => '\n', "\t" => '\t', '/' => '\/', "\r" => '\r', "\b" => '\b', "\f" => '\f', '"' => '\"', chr(0x08) => '\b', chr(0x0C) => '\f');
		$value  = strtr($value, $replace);
		return '"' . $value . '"';
	} elseif (is_bool($value)) {
		return $value ? 'true' : 'false';
	} elseif (empty($value)) {
		return '""';
	} else {
		return $value;
	}
}

function util_json_decode($value) {
	if( function_exists('json_decode')) {
		return json_decode($value);
	}
	if (!class_exists('JSON')) {
		include_once(CONFIG_PATH . '/includes/cls.json.php');
	}
	
	$json = new JSON();
	return $json->decode($value);
}

function util_load_file($filename, $filepath, $default_filename = '', $default_filepath = '', $check = false) {
	//global $request_uri, $request_type, $request_link, $request_param;
	//global $adb, $tpl, $injectObj, $messagestackObj, $pcObj;
	//
	if( util_not_null($filename) == false || util_not_null($filepath) == false ) {
		return false;
	}
	$count = 0;
	if( $check == true ) {
		if( $default_filepath != '' && $default_filename == '' ) {
			$default_filename = $filename;
		}
		if( $default_filename != '' && $default_filepath != '' ) {
			if( file_exists($default_filepath . $default_filename) ) {
				include_once($default_filepath . $default_filename);
			} elseif( file_exists($filepath . $filename) ) {
				include_once($filepath . $filename);
			} else {
				$count++;
			}
		} else {
			if( file_exists($filepath . $filename) ) {
				include_once($filepath . $filename);
			} else {
				$count++;
			}
		}
	} else {
		if( $default_filepath != '' && $default_filename == '' ) {
			$default_filename = $filename;
		}
		if( $default_filename != '' && $default_filepath != '' ) {
			if( file_exists($filepath . $filename) ) {
				include_once($filepath . $filename);
			} elseif( file_exists($default_filepath . $default_filename) ) {
				include_once($default_filepath . $default_filename);
			} else {
				$count++;
			}
		} else {
			if( file_exists($filepath . $filename) ) {
				include_once($filepath . $filename);
			} else {
				$count++;
			}
		}
	}
	
	return $count;
}

function util_load_files($filenames, $check = false) {
	if( util_not_null($filename) == false ) {
		return false;
	}
	$count = 0;
	if( $check == true ) {
		if( is_array($filenames) ) {
			foreach($filenames as $filename) {
				if( util_not_null($filename) && file_exists($filename) ) {
					include_once($filename);
				} else {
					$count++;
				}
			}
		} else {
			if( file_exists($filename) ) {
				include_once($filename);
			}
		}
	} else {
		if( is_array($filenames) ) {
			foreach($filenames as $filename) {
				if( util_not_null($filename) ) {
					include_once($filename);
				} else {
					$count++;
				}
			}
		} else {
			include_once($filename);
		}
	}
	
	return $count;
}

function util_href_link($page, $parameters, $ssl = '', $x = '', $y = '') {
	$link = $page;
	
	if( util_not_null($parameters) ) {
		$link .= '?' . $parameters;
	}
	
	return $link;
}

function util_random($length) {
	$hash = '';
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
	$max = strlen($chars) - 1;
	PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
	for($i = 0; $i < $length; $i++) {
		$hash .= $chars[mt_rand(0, $max)];
	}
	
	return $hash;
}

function util_generatekey() {
	$random = random(32);
	$info = md5($_SERVER['SERVER_SOFTWARE'].$_SERVER['SERVER_NAME'].$_SERVER['SERVER_ADDR'].$_SERVER['SERVER_PORT'].$_SERVER['HTTP_USER_AGENT'].time());
	$return = '';
	for($i=0; $i<64; $i++) {
		$p = intval($i/2);
		$return[$i] = $i % 2 ? $random[$p] : $info[$p];
	}
	
	return implode('', $return);
}

function util_create_random($min = null, $max = null) {
	static $seeded;
	
	if( !isset($seeded) ) {
		 mt_srand((double)microtime()*1000000);
		 $seeded = true;
	}
	
	if( isset($min) && isset($max) ) {
		if( $min >= $max ) {
			return $min;
		} else {
			return mt_rand($min, $max);
		}
	} else {
		return mt_rand();
	}
}

function util_create_random_value($length, $type) {
	if( ($type != 'mixed') && ($type != 'chars') && ($type != 'digits') && ($type != 'fullmixed') && ($type != 'fullchars') ) {
		return false;
	}
	
	$rand_value = '';
	while( strlen($rand_value) < $length ) {
		if( $type == 'digits' ) {
			$char = util_create_random(0, 9);
		} else {
			$char = chr(util_create_random(0, 255));
		}
		
		if( $type == 'mixed' ) {
			if( ereg('^[a-zA-Z0-9]$', $char) ) {
				$rand_value .= $char;
			}
		} elseif( $type == 'fullmixed' ) {
			if( ereg('^[a-zA-Z0-9]$', $char) ) {
				$rand_value .= $char;
			}
		} elseif( $type == 'chars' ) {
			if( ereg('^[a-z]$', $char) ) {
				$rand_value .= $char;
			}
		} elseif( $type == 'fullchars' ) {
			if( ereg('^[a-zA-Z]$', $char) ) {
				$rand_value .= $char;
			}
		} elseif( $type == 'digits' ) {
			if( ereg('^[0-9]$', $char) ) {
				$rand_value .= $char;
			}
		}
	}
	
	return $rand_value;
}

// Wrapper function for round()
function util_round($number, $precision) {
	if( strpos($number, '.') && (strlen(substr($number, strpos($number, '.')+1)) > $precision) ) {
		$number = substr($number, 0, strpos($number, '.') + 1 + $precision + 1);
		
		if( substr($number, -1) >= 5 ) {
			if( $precision > 1 ) {
				$number = substr($number, 0, -1) + ('0.' . str_repeat(0, $precision-1) . '1');
			} elseif( $precision == 1 ) {
				$number = substr($number, 0, -1) + 0.1;
			} else {
				$number = substr($number, 0, -1) + 1;
			}
		} else {
			$number = substr($number, 0, -1);
		}
	}
	
	return $number;
}

function util_page_parse_time($format = true) {
	$time_start = explode(' ', PAGE_PARSE_START_TIME);
	$time_end = explode(' ', microtime());
	$parse_time = number_format(($time_end[1] + $time_end[0] - ($time_start[1] + $time_start[0])), 3);
	
	if( $format == true ) {
		return '<div id="pagetime">' . $parse_time . '</div>';
	}
	return $parse_time;
}

// parse date
// $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
function util_parse_date($raw_date) {
	$date_array = array();
	
	if( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '') ) {
		return false;
	}
	
	$year = (int)substr($raw_date, 0, 4);
	$month = (int)substr($raw_date, 5, 2);
	$day = (int)substr($raw_date, 8, 2);
	$hour = (int)substr($raw_date, 11, 2);
	$minute = (int)substr($raw_date, 14, 2);
	$second = (int)substr($raw_date, 17, 2);

	$date_array = array(
				'year' => $year,
				'month' => $month,
				'day' => $day,
				'hour' => $hour,
				'minute' => $minute,
				'second' => $second
					);
	return $date_array;
}

// check a string is time
// $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
function util_istime($raw_date) {
	$pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';
	
	return preg_match($pattern, $raw_date);
}

// make time from raw date
// $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
function util_mktime($raw_date) {
	if( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '') ) {
		return 0;
	}
	
	$year = (int)substr($raw_date, 0, 4);
	$month = (int)substr($raw_date, 5, 2);
	$day = (int)substr($raw_date, 8, 2);
	$hour = (int)substr($raw_date, 11, 2);
	$minute = (int)substr($raw_date, 14, 2);
	$second = (int)substr($raw_date, 17, 2);
	
	return mktime($hour,$minute,$second,$month,$day,$year);
}

// Output a raw date string in the selected locale date format
// $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
function util_date_long($raw_date, $date_format_long = '') {
	if( ($raw_date == '0000-00-00 00:00:00') || ($raw_date == '') ) {
		return false;
	}
	
	$year = (int)substr($raw_date, 0, 4);
	$month = (int)substr($raw_date, 5, 2);
	$day = (int)substr($raw_date, 8, 2);
	$hour = (int)substr($raw_date, 11, 2);
	$minute = (int)substr($raw_date, 14, 2);
	$second = (int)substr($raw_date, 17, 2);
	
	return strftime($date_format_long, mktime($hour,$minute,$second,$month,$day,$year));
}

// Output a raw date string in the selected locale date format
// $raw_date needs to be in this format: YYYY-MM-DD HH:MM:SS
// NOTE: Includes a workaround for dates before 01/01/1970 that fail on windows servers
function util_date_short($raw_date) {
	if( ($raw_date == '0000-00-00 00:00:00') || empty($raw_date) ) {
		return false;
	}
	
	$year = substr($raw_date, 0, 4);
	$month = (int)substr($raw_date, 5, 2);
	$day = (int)substr($raw_date, 8, 2);
	$hour = (int)substr($raw_date, 11, 2);
	$minute = (int)substr($raw_date, 14, 2);
	$second = (int)substr($raw_date, 17, 2);
	
	if( @date('Y', mktime($hour, $minute, $second, $month, $day, $year)) == $year ) {
		return date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, $year));
	} else {
		return ereg_replace('2037' . '$', $year, date(DATE_FORMAT, mktime($hour, $minute, $second, $month, $day, 2037)));
	}
}

// Check date
function util_checkdate($date_to_check, $format_string, &$date_array) {
	$separator_idx = -1;
	
	$separators = array('-', ' ', '/', '.');
	$month_abbr = array('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec');
	$no_of_days = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	
	$format_string = strtolower($format_string);
	
	if( strlen($date_to_check) != strlen($format_string)) {
		return false;
	}
	
	$size = sizeof($separators);
	for ($i=0; $i<$size; $i++) {
		$pos_separator = strpos($date_to_check, $separators[$i]);
		if( $pos_separator != false) {
			$date_separator_idx = $i;
			break;
		}
	}
	
	for ($i=0; $i<$size; $i++) {
		$pos_separator = strpos($format_string, $separators[$i]);
		if( $pos_separator != false) {
			$format_separator_idx = $i;
			break;
		}
	}
	
	if( $date_separator_idx != $format_separator_idx) {
		return false;
	}
	
	if( $date_separator_idx != -1) {
		$format_string_array = explode( $separators[$date_separator_idx], $format_string );
		if( sizeof($format_string_array) != 3) {
			return false;
		}
		
		$date_to_check_array = explode( $separators[$date_separator_idx], $date_to_check );
		if( sizeof($date_to_check_array) != 3) {
			return false;
		}
		
		$size = sizeof($format_string_array);
		for ($i=0; $i<$size; $i++) {
			if( $format_string_array[$i] == 'mm' || $format_string_array[$i] == 'mmm') $month = $date_to_check_array[$i];
			if( $format_string_array[$i] == 'dd') $day = $date_to_check_array[$i];
			if( ($format_string_array[$i] == 'yyyy') || ($format_string_array[$i] == 'aaaa') ) $year = $date_to_check_array[$i];
		}
	} else {
		if( strlen($format_string) == 8 || strlen($format_string) == 9) {
			$pos_month = strpos($format_string, 'mmm');
			if( $pos_month != false) {
				$month = substr( $date_to_check, $pos_month, 3 );
				$size = sizeof($month_abbr);
				for ($i=0; $i<$size; $i++) {
					if( $month == $month_abbr[$i] ) {
						$month = $i;
						break;
					}
				}
			} else {
				$month = substr($date_to_check, strpos($format_string, 'mm'), 2);
			}
		} else {
			return false;
		}
	
		$day = substr($date_to_check, strpos($format_string, 'dd'), 2);
		$year = substr($date_to_check, strpos($format_string, 'yyyy'), 4);
	}

	if( strlen($year) != 4) {
		return false;
	}

	if( !settype($year, 'integer') || !settype($month, 'integer') || !settype($day, 'integer')) {
		return false;
	}
	
	if( $month > 12 || $month < 1) {
		return false;
	}
	
	if( $day < 1) {
		return false;
	}

	if( util_is_leap_year($year)) {
		$no_of_days[1] = 29;
	}

	if( $day > $no_of_days[$month - 1] ) {
		return false;
	}

	$date_array = array($year, $month, $day);
	
	return true;
}

// Check if year is a leap year
function util_is_leap_year($year) {
	if( $year % 100 == 0) {
		if( $year % 400 == 0 ) {
			return true;
		}
	} else {
		if( ($year % 4) == 0 ) {
			return true;
		}
	}
	
	return false;
}

//email
function util_checkemail($email) {
	$pattern = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,5}\$/i";
	if( strpos($email, '@') !== false && strpos($email, '.') !== false ) {
		if( preg_match($pattern, $email) ) {
			return true;
		}
	}
	
	return false;
}

function util_check_email($email) {
	//$pattern = "/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/";
	$pattern = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,5}\$/i";
	if( strpos($email, "@") !== false && strpos($email, ".") !== false ) {
		if( preg_match($pattern, $email) ) {
			return true;
		}
	}
	
	return false;
}

function util_validate_email($email) {
	$valid_address = true;
	
	$mail_pat = '^(.+)@(.+)$';
	$valid_chars = "[^] \(\)<>@,;:\.\\\"\[]";
	$atom = "$valid_chars+";
	$quoted_user='(\"[^\"]*\")';
	$word = "($atom|$quoted_user)";
	$user_pat = "^$word(\.$word)*$";
	$ip_domain_pat='^\[([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\]$';
	$domain_pat = "^$atom(\.$atom)*$";
	
	if( eregi($mail_pat, $email, $components) ) {
		$user = $components[1];
		$domain = $components[2];
		// validate user
		if( eregi($user_pat, $user) ) {
			// validate domain
			if( eregi($ip_domain_pat, $domain, $ip_components) ) {
				// this is an IP address
				for($i=1;$i<=4;$i++) {
					if( $ip_components[$i] > 255 ) {
						$valid_address = false;
						break;
					}
				}
			} else {
				// Domain is a name, not an IP
				if( eregi($domain_pat, $domain) ) {
					/*domain name seems valid, but now make sure that it ends in a valid TLD or ccTLD
					 and that there's a hostname preceding the domain or country. */
					$domain_components = explode(".", $domain);
					// Make sure there's a host name preceding the domain.
					if( sizeof($domain_components) < 2 ) {
						$valid_address = false;
					} else {
						$top_level_domain = strtolower($domain_components[sizeof($domain_components)-1]);
						// Allow all 2-letter TLDs (ccTLDs)
						if( eregi('^[a-z][a-z]$', $top_level_domain) != 1 ) {
							$tld_pattern = '';
							// Get authorized TLDs from text file
							$tlds = file(CONFIG_PATH . CONFIG_DIR_INCLUDES . 'tld.txt');
							while(list(,$line) = each($tlds) ) {
								// Get rid of comments
								$words = explode('#', $line);
								$tld = trim($words[0]);
								// TLDs should be 3 letters or more
								if( eregi('^[a-z]{3,}$', $tld) == 1 ) {
									$tld_pattern .= '^' . $tld . '$|';
								}
							}
							// Remove last '|'
							$tld_pattern = substr($tld_pattern, 0, -1);
							if( eregi("$tld_pattern", $top_level_domain) == 0 ) {
								$valid_address = false;
							}
						}
					}
				} else {
					$valid_address = false;
				}
			}
		} else {
			$valid_address = false;
		}
	} else {
		$valid_address = false;
	}
	
	/*
	if( $valid_address ) {
		if( !checkdnsrr($domain, "MX") && !checkdnsrr($domain, "A") ) {
			$valid_address = false;
		}
	}
	*/
	return $valid_address;
}

function util_mail($to_name, $to_email_address, $email_subject, $email_text, $from_name, $from_email_address) {
	require_once(CONFIG_PATH . CONFIG_DIR_CLASSES . 'lib.mime.class.php');
	require_once(CONFIG_PATH . CONFIG_DIR_CLASSES . 'lib.email.class.php');
	/*
	if( defined('CONFIG_EMAIL_CHARSET') ) {
		$emailcharset = CONFIG_EMAIL_CHARSET;
		$email_subject = iconv("UTF-8", $emailcharset, $email_subject);
		$to_name = iconv("UTF-8", $emailcharset, $to_name);
		$from_name = iconv("UTF-8", $emailcharset, $from_name);
		$email_text = iconv("UTF-8", $emailcharset, $email_text);
	}
	*/
	// Instantiate a new mail object
	$message = new LibEmail(array('X-Mailer: windows Mailer'));
	
	// Build the text version
	$text = strip_tags($email_text);
	// html 
	if( CONFIG_EMAIL_USE_HTML == 'true' ) {
		$message->add_html($email_text, $text);
	} else {
		$message->add_text($text);
	}
	// Send message
	$message->build_message();
		
	$message->send($to_name, $to_email_address, $from_name, $from_email_address, $email_subject);
}

//check file is image by its suffix, common formats
function util_is_image($filename) {
	if( (strtolower(substr($filename, -4)) == '.gif') || (strtolower(substr($filename, -4)) == '.png') 
		|| (strtolower(substr($filename, -4)) == '.jpg') || (strtolower(substr($filename, -5)) == '.jpeg') 
		|| (strtolower(substr($filename, -4)) == '.bmp') || (strtolower(substr($filename, -5)) == '.icon') ) {
		
		return true;
	}
	return false;
}

function util_get_file_suffix($filename) {
	$file_suffix_pos = strrpos($filename, '.');
	if( $file_suffix_pos === false ) {
		return '';
	} else {
		$file_suffix = strtolower(substr($filename, $file_suffix_pos));
		return $file_suffix;
	}
}

function util_get_file_type($filename) {
	$file_suffix = util_get_file_suffix($filename);
	
	if( $file_suffix == '' ) {
		return '';
	} else {
		return substr($file_suffix, 1);
	}
}

function util_get_product_image($filename, $thumb = '') {
	global $SETTINGS;
	
	if( $SETTINGS['image_thumb_enabled'] == false ) {
		return $filename;
	}
	if( $thumb != '' ) {
		$thumb .= '/';
	}
	$filename = dirname($filename) . '/' . $thumb . basename($filename);
	
	return $filename;
}

function util_shipping_icon_image($icon, $title) {
	return '<img src="' . CONFIG_URL_HTTP . CONFIG_DIR_IMAGES . 'icons/' . $icon . '" title="' . $title . '">';
}

function util_get_imagesize($filename, $width = '400', $height = '400') {
	if( $image_size = @getimagesize($filename) ) {
		$ratio = $image_size[0] / $image_size[1];
		$ratio_set = $width / $height;
		if( $ratio >= $ratio_set ) {
			$height = ceil($image_size[1] * ( $width / $image_size[0] ));
		} else {
			$width = ceil($image_size[0] * ( $height / $image_size[1] ));
		}
	}
	
	$image_size = array(
				'width' => $width,
				'height' => $height
					);
	return $image_size;
}

function util_get_imagesize_adjust($width_s, $height_s, $width = '500', $height = '500') {
	if( ($width_s < 1) || ($height_s < 1) ) {
		$image_size = array(
					'width' => $width,
					'height' => $height
						);
		return $image_size;
	}
	$ratio = $width_s / $height_s;
	$ratio_set = $width / $height;
	if( $ratio >= $ratio_set ) {
		$height = ceil($height_s * ( $width / $width_s ));
	} else {
		$width = ceil($width_s * ( $height / $height_s ));
	}
	
	$image_size = array(
				'width' => $width,
				'height' => $height
					);
	return $image_size;
}

function util_create_filename($filename, $path) {
	$new_filename = '';
	
	if( file_exists($path . $filename) ) {
		$file_suffix_pos = strrpos($filename, '.');
		$random = util_create_random_value('5', 'mixed');
		if( $file_suffix === false ) {
			$new_filename = $filename . '-' . $random;
		} else {
			$new_filename = substr($filename, 0, $file_suffix_pos) . '-' . $random . substr($filename, $file_suffix_pos);
		}
		//return util_create_filename($new_filename, $path);
		return util_create_filename($filename, $path);
	} else {
		return $filename;
	}
}

//mkdir 
function util_mkdir($dir_path, $mod=0777) {
	$cur_dir = CONFIG_PATH;
	if( is_dir($cur_dir . $dir_path) ) {
		return true;
	}
	$arr_path = explode('/', $dir_path);
	foreach($arr_path as $val) {
		if( !empty($val) ) {
			$cur_dir .= $val;
			if( is_dir($cur_dir) ) {
				$cur_dir .= '/';
				continue;
			}
			if( mkdir($cur_dir, $mod) ) {
				$cur_dir .= '/';
				fclose(fopen($cur_dir.'index.html', 'w'));
			} else {
				return false;
			}
		}
	}
	
	return true;
}

//delete directory and its subs directory and files
function util_rmdir($dir) {
	$dir = str_replace(array('..', "\n", "\r"), array('', '', ''), $dir);
	$r = false;
	if( is_dir($dir) ) {
		$d = @dir($dir);
		if( $d ) {
			while(false !== ($entry = $d->read())) {
				if($entry!='.' && $entry!='..') {
					$entry = $dir.'/'.$entry;
					if(is_dir($entry)) {
						util_rmdir($entry);
					} else {
						@unlink($entry);
					}
				}
			}
			$d->close();
			$r = @rmdir($dir);
		}
	} else {
		$r = @unlink($dir);
	}
	
	return $r;
}

//list array to rows array
function util_array_convert_rows($data_array, $column_nums = '3', $matrix_full = true) {
	if( !is_array($data_array) ) {
		return $data_array;
	}
	
	$row = 0;
	$col = 0;
	$data_new_array = array();
	for($i=0, $n=sizeof($data_array); $i<$n; $i++) {
		$data_new_array[$row][$col] = $data_array[$i];
		
		$col ++;
		if( $col >= $column_nums ) {
			$col = 0;
			$row++;
		}
	}
	
	if( $matrix_full ) {
		if( $col > 0 ) {
			for($i=$col; $i< $column_nums; $i++) {
				$data_new_array[$row][$i] = array();
			}
		}
	}
	
	return $data_new_array;
}

//fopen 
function util_fopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	$return = '';
	$matches = parse_url($url);
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'].'?'.$matches['query'].'#'.$matches['fragment'] : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;

	if( $post) {
		$out = "POST $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		//$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: '.strlen($post)."\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		//$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
	if(!$fp) {
		return '';
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if(!$status['timed_out'] ) {
			while (!feof($fp)) {
				if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
					break;
				}
			}

			$stop = false;
			while(!feof($fp) && !$stop) {
				$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
				$return .= $data;
				if( $limit) {
					$limit -= strlen($data);
					$stop = $limit <= 0;
				}
			}
		}
		@fclose($fp);
		
		return $return;
	}
}

//cache
function util_cache_clear() {

}

//debug display
function d($data) {
	echo '<pre>';print_r($data);echo '</pre>';
}

//debug display and then exit
function de($data) {
	echo '<pre>';print_r($data);echo '</pre>';
	exit();
}

//
function util_get_navigation($link_array, $total, $limit_start, $limit_length, $max_page_links = '5', $page_name = 'page') {
	global $LANGUAGE;
	$lang_nav = $LANGUAGE['navigation'];
	
	//
	$page = $link_array['page'];
	$parameters = $link_array['parameters'];
	
	if( $limit_start <= 0 ) {
		$limit_start = 0;
	}
	if( $limit_length < 0 ) {
		$limit_length = 10;
	}
	//page
	$current_page_number = intval($limit_start / $limit_length);
	$current_page_number++;
	if( $limit_start % $limit_length ) {
		$current_page_number++;
	}
	$number_of_pages = intval($total / $limit_length);
	if( $total % $limit_length ) {
		$number_of_pages++;
	}
	//window
	$cur_window_num = intval($current_page_number / $max_page_links);
	if( $current_page_number % $max_page_links ) {
		$cur_window_num++;
	}
	$max_window_num = intval($number_of_pages / $max_page_links);
	if( $number_of_pages % $max_page_links ) {
		$max_window_num++;
	}
	
	//LINKS
	$links = '';
	// previous button - not displayed on first page
	if( $current_page_number > 1 ) {
		$links .= '<a href="' . util_href_link($page, $parameters . $page_name . '=' . ($current_page_number - 1)) . '" title="' . $lang_nav['pre_title'] . '">' . $lang_nav['pre'] . '</a>&nbsp;&nbsp;';
	}
	// previous window of pages
	if( $cur_window_num > 1 ) {
		$links .= '<a href="' . util_href_link($page, $parameters . $page_name . '=' . (($cur_window_num - 1) * $max_page_links)) . '" title="' . sprintf($lang_nav['pre_set_of_no_page_title'], $max_page_links) . '">' . $lang_nav['pre_set_of_no_page'] . '</a>&nbsp;&nbsp;';
	}
	// page nn button
	for($jump_to_page = 1 + (($cur_window_num - 1) * $max_page_links);
		 ($jump_to_page <= ($cur_window_num * $max_page_links)) && ($jump_to_page <= $number_of_pages); 
		 $jump_to_page++ ) {
		if( $jump_to_page == $current_page_number ) {
			$links .= '<b>' . $jump_to_page . '</b>&nbsp;&nbsp;';
		} else {
			$links .= '<a href="' . util_href_link($page, $parameters . $page_name . '=' . $jump_to_page) . '" title="' . sprintf($lang_nav['next_set_of_no_page'], $jump_to_page) . '">' . $jump_to_page . '</a>&nbsp;&nbsp;';
			
		}
	}
	// next window of pages
	if( $cur_window_num < $max_window_num ) {
		$links .= '<a href="' . util_href_link($page, $parameters . $page_name . '=' . (($cur_window_num) * $max_page_links + 1)) . '" title="' . sprintf($lang_nav['next_set_of_no_page_title'], $max_page_links) . '">' . $lang_nav['next_set_of_no_page'] . '</a>&nbsp;&nbsp;';
	}
	// next button
	if( ($current_page_number < $number_of_pages) && ($number_of_pages != 1) ) {
		$links .= '<a href="' . util_href_link($page, $parameters . $page_name . '=' . ($current_page_number + 1)) . '" title="' . $lang_nav['next_title'] . '">' . $lang_nav['next'] . '</a>&nbsp;&nbsp;';
	}
	
	//COUNT
	$from_num = $limit_start + 1;
	$to_num = $limit_start + $limit_length;
	if( $to_num >= $total ) {
		$to_num = $total;
	}
	$count = sprintf($lang_nav['count'], $from_num, $to_num, $total);
	
	//SHOW
	if( $total <= $limit_length ) {
		$show = '0';
	} else {
		$show = '1';
	}
	
	//RETURN
	$navigation = array(
				'show' => $show,
				'links' => $links,
				'count' => $count,
					);
	return $navigation;
}

function util_common_navigation($link_array, $total, $limit_start, $limit_length, $max_page_links = '5', $page_name = 'page') {
	global $LANGUAGE;
	$lang_nav = $LANGUAGE['navigation'];
	
	//
	$page = $link_array['page'];
	$parameters = $link_array['parameters'];
	
	if( $limit_start <= 0 ) {
		$limit_start = 0;
	}
	if( $limit_length < 0 ) {
		$limit_length = 10;
	}
	//page
	$current_page_number = intval($limit_start / $limit_length);
	$current_page_number++;
	if( $limit_start % $limit_length ) {
		$current_page_number++;
	}
	$number_of_pages = intval($total / $limit_length);
	if( $total % $limit_length ) {
		$number_of_pages++;
	}
	//window
	$cur_window_num = intval($current_page_number / $max_page_links);
	if( $current_page_number % $max_page_links ) {
		$cur_window_num++;
	}
	$max_window_num = intval($number_of_pages / $max_page_links);
	if( $number_of_pages % $max_page_links ) {
		$max_window_num++;
	}
	
	//LINKS
	$links = '';
	// previous button - not displayed on first page
	if( $current_page_number > 1 ) {
		$links .= '<li class="prev"><a href="' . util_href_link($page, $parameters . $page_name . '=' . ($current_page_number - 1)) . '" title="' . $lang_nav['pre_title'] . '">' . $lang_nav['pre'] . '</a></li>';
	}
	// previous window of pages
	if( $cur_window_num > 1 ) {
		$links .= '<li class="prevp"><a href="' . util_href_link($page, $parameters . $page_name . '=' . (($cur_window_num - 1) * $max_page_links)) . '" title="' . sprintf($lang_nav['pre_set_of_no_page_title'], $max_page_links) . '">' . $lang_nav['pre_set_of_no_page'] . '</a></li>';
	}
	// page nn button
	for($jump_to_page = 1 + (($cur_window_num - 1) * $max_page_links);
		 ($jump_to_page <= ($cur_window_num * $max_page_links)) && ($jump_to_page <= $number_of_pages); 
		 $jump_to_page++ ) {
		if( $jump_to_page == $current_page_number ) {
			$links .= '<li><b>' . $jump_to_page . '</b></li>';
		} else {
			$links .= '<li><a href="' . util_href_link($page, $parameters . $page_name . '=' . $jump_to_page) . '" title="' . sprintf($lang_nav['page_no_title'], $jump_to_page) . '">' . $jump_to_page . '</a></li>';
			
		}
	}
	// next window of pages
	if( $cur_window_num < $max_window_num ) {
		$links .= '<li class="nextp"><a href="' . util_href_link($page, $parameters . $page_name . '=' . (($cur_window_num) * $max_page_links + 1)) . '" title="' . sprintf($lang_nav['next_set_of_no_page_title'], $max_page_links) . '">' . $lang_nav['next_set_of_no_page'] . '</a></li>';
	}
	// next button
	if( ($current_page_number < $number_of_pages) && ($number_of_pages != 1) ) {
		$links .= '<li class="next"><a href="' . util_href_link($page, $parameters . $page_name . '=' . ($current_page_number + 1)) . '" title="' . $lang_nav['next_title'] . '">' . $lang_nav['next'] . '</a></li>';
	}
	
	//COUNT
	$from_num = $limit_start + 1;
	$to_num = $limit_start + $limit_length;
	if( $to_num >= $total ) {
		$to_num = $total;
	}
	$count = sprintf($lang_nav['count'], $from_num, $to_num, $total);
	
	//SHOW
	if( $total <= $limit_length ) {
		$show = '0';
	} else {
		$show = '1';
	}
	
	//RETURN
	$navigation = array(
				'show' => $show,
				'links' => $links,
				'count' => $count,
					);
	return $navigation;
}

function util_common_js_navigation($js, $total, $page = '1', $max_nums_of_page = '10', $max_pages_of_window = '5') {
	global $LANGUAGE;
	$lang_nav = $LANGUAGE['navigation'];
	
	//
	$pages_nums = intval($total / $max_nums_of_page);
	if( $total % $max_nums_of_page ) {
		$pages_nums++;
	}
	
	//window
	$cur_window_num = intval($page / $max_pages_of_window);
	if( $page % $max_pages_of_window ) {
		$cur_window_num++;
	}
	$max_window_num = intval($pages_nums / $max_pages_of_window);
	if( $pages_nums % $max_pages_of_window ) {
		$max_window_num++;
	}
	
	//
	if( is_array($js) ) {
		$js_function = $js['f'];
		$js_args = $js['a'];
		//$js . '(\'' . $tid . '\', 
		if( !is_array($js_args) ) {
			$js_args = array($js_args);
		}
		$i = 0;
		$js_p = $js . '(';
		foreach($js_args as $k => $v) {
			if( $i > 0 ) {
				$js_p .= ',';
			}
			$js .= '\'' . $v . '\'';
			$i++;
		}
	} else {
		$js_p = $js . '(';
	}
	$js_s = ');';
	
	//
	$links = '';
	if( $page > 1 ) {
		$links .= '<li><a href="javascript:void(0);" onClick="' . $js_p . '\'1\'' . $js_s . '">' . $lang_nav['t_first'] . '</a></li>';
		$links .= '<li><a href="javascript:void(0);" onClick="' . $js_p . '\'' . ($page - 1) . '\'' . $js_s . '">' . $lang_nav['t_pre'] . '</a></li>';
	}
	if( $cur_window_num > 1 ) {
		$links .= '<li><a href="javascript:void(0);" onClick="' . $js_p . '\'' . (($cur_window_num - 1) * $max_pages_of_window) . '\'' . $js_s . '">&lt;&lt;</a></li>';
	}
	for($jump_to_page = 1 + (($cur_window_num - 1) * $max_pages_of_window); ($jump_to_page <= ($cur_window_num * $max_pages_of_window)) && ($jump_to_page <= $pages_nums); $jump_to_page++ ) {
		if( $jump_to_page == $page ) {
			$links .= '<li><b>' . $jump_to_page . '</b></li>';
		} else {
			$links .= '<li><a href="javascript:void(0);" onClick="' . $js_p . '\'' . $jump_to_page . '\'' . $js_s . '">' . $jump_to_page . '</a></li>';
		}
	}

	if( $cur_window_num < $max_window_num ) {
		$links .= '<li><a href="javascript:void(0);" onClick="' . $js_p . '\'' . ($cur_window_num * $max_pages_of_window + 1) . '\'' . $js_s . '">' . $lang_nav['next_set_of_no_page'] . '</a></li>';
	}
	if( ($page < $pages_nums) && ($pages_nums != 1) ) {
		$links .= '<li><a href="javascript:void(0);" onClick="' . $js_p . '\'' . ($page + 1) . '\'' . $js_s . '">' . $lang_nav['t_next'] . '</a></li>';
	}
	if( ($page < $pages_nums) && ($cur_window_num < $max_window_num) ) {
		$links .= '<li><a href="javascript:void(0);" onClick="' . $js_p . '\'' . ($pages_nums - 1) . '\'' . $js_s . '">' . $lang_nav['t_last'] . '</a></li>';
	}
	
	//COUNT
	$limit_start = ($page - 1) * $max_nums_of_page;
	$limit_length = $max_nums_of_page;
	$from_num = $limit_start + 1;
	$to_num = $limit_start + $limit_length;
	if( $to_num >= $total ) {
		$to_num = $total;
	}
	$count = sprintf($lang_nav['count'], $from_num, $to_num, $total);
	
	//SHOW
	if( $total <= $limit_length ) {
		$show = '0';
	} else {
		$show = '1';
	}
	
	//RETURN
	$navigation = array(
				'show' => $show,
				'links' => $links,
				'count' => $count,
					);
	return $navigation;
}

function util_common_js_item_navigation($js, $tid, $total, $page = '1', $max_nums_of_page = '10', $max_pages_of_window = '5') {
	$js = array('f' => $js, 'a' => $tid);
	
	return util_common_js_navigation($js, $total, $page, $max_nums_of_page, $max_pages_of_window);
}

function util_content_comments_navigation($tid, $total, $page = '1', $max_nums_of_page = '10', $max_pages_of_window = '5') {
	return util_common_js_item_navigation('PJS.content.loadcomments', $tid, $total, $page, $max_nums_of_page, $max_pages_of_window);
}

function util_product_comments_navigation($tid, $total, $page = '1', $max_nums_of_page = '10', $max_pages_of_window = '5') {
	return util_common_js_item_navigation('PJS.product.loadcomments', $tid, $total, $page, $max_nums_of_page, $max_pages_of_window);
}
//
?>